package com.LeetCode.doublePair;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 三数之和
 */
public class ThreeSum {

    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        int len = nums.length;
        if(len < 3) return res;
        Arrays.sort(nums);
        for(int i = 0; i<len; i++){
            if(nums[i] > 0) break;
            if(i>0 && nums[i] == nums[i-1]) continue;
            int target = - nums[i];
            int l = i + 1, r = len - 1;
            while(l < r){
                int sum = nums[l] + nums[r];
                if(sum == target){
                    res.add(new ArrayList<>(Arrays.asList(nums[l], nums[r] , target)));
                    while(l < r && nums[l] == nums[l+1]) l++;
                    while(l < r && nums[r] == nums[r-1]) r--;
                    l++;
                    r--;
                }else if(sum < target){
                    l++;
                }else{
                    r--;
                }
            }
        }
        return res;
    }

    @Test
    public void test(){
        int[] arr = {-1, 0, 1, 2, -1, -4};
        threeSum(arr).forEach( System.out::println);
    }
}
